import React, { Component, PureComponent } from 'react';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Card, Divider, Button, Icon, Modal,Form } from 'antd';
import AdvancedSearch from '@/components/AdvancedSearch';
import AdvancedTable from '@/components/AdvancedTable';
import IotDeviceFind from '@/components/IotDeviceFind';
import styles from './deviceType.less';
import IotDeviceType from '@/components/IotDeviceType';
import { deleteById, retrieval } from '@/services/requestData';
import { openNotificationWithIcon, QueryCond, deleteInvalidSigns } from '@/utils/tools';

/**
 * 设备列表
 * @author nyy 2019-04-21
 */
@connect(({ deviceType_add, loading }) => ({
  deviceType_add,
  loading: loading.effects['models/device/deviceType_add'],
}))
export default class DeviceType extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datalines: [],
      loading: false,
      visible: false,
      visibleFind:false,
      row: {},
    };
    // 高级检索配置
    this.master = 'devicetype';
    this.items = [
      {  key: 'device_type_name',  name: '设备名称类型',  type: 'input',  first: true,  datatable: this.master,  mode: 3,},
    ];
    // 表格栏目对应字段配置
    this.columns = [
      { title: '设备类型名称', dataIndex: 'device_type_name', sorter: true, first: true },
      { title: '操作', dataIndex: '$$operations', render: (row) => {
        return (<div>
          <Button className={styles.buttonFind} onClick={() => {
              console.log(row);
              this.setState({
                  row:row,
                  visibleFind: true,
              });
          }}>查看订阅</Button>
          <Button className={styles.buttonCheck} onClick={() => {
              console.log(row);
              this.setState({
                  row:row,
                  visible: true,
                  disabled:true,
              });
          }}>查看</Button>
          <Button className={styles.buttonEdit} onClick={() => {
              let handle = row.getHandle();
              this.setState({
                  row:row,
                  visible: true,
                  disabled:false,
                  handle:handle,
              });
              handle.updateList();
          }}>修改</Button>
          <Button className={styles.buttonDelete} onClick={() => {
              Modal.confirm({
                title: '删除',
                content: '确定要删除该数据吗？',
                onOk() {
                  let response = deleteById("DeviceType",row.id);
                  response.then(content => {
                    openNotificationWithIcon("success","删除成功","恭喜，删除成功！");
                    let handle = row.getHandle();
                    handle.updateList();
                  }).catch(e=>{
                    openNotificationWithIcon("error","加载失败","无法获得数据，请检查信息是否正确");
                  });
                },
                onCancel() {},
              });
          }}>删除</Button>
          </div>);
      } },
    ];
    // 特殊控制按钮配置
    this.controllers = [
      {
        name: '添加',
        icon: 'file',
        callback: handle => {
          this.setState({
            row: {},
            visible: true,
            disabled: false,
            handle: handle,
          });
          handle.updateList();
        },
      },
    ];
  }

  handleSubmit = (err, values) => {
    const { dispatch } = this.props;
    if (!err) {
        // let conds = new QueryCond();
        // conds.exactQuery('device_type_name', deleteInvalidSigns(values.device_type_name));
        // let searchParam = {datatable:"devicetype",conds:conds.getConds()};
        // let response = retrieval(searchParam)
        // response.then(e=>{
        //   if(e.length>0){
        //     openNotificationWithIcon("error","提交失败","提交失败，列表中已存在该设备类型！");
        //   }else{
            let form = {};
            let objKeys = Object.keys(values);
            for(var one of objKeys){
              form[one] = values[one];
            }
            form.id = this.state.row.id;
            console.log(form);
            dispatch({
              type: 'deviceType_add/addDevice',
              payload: {
                datatable: "DeviceType",
                body: form,
              },
              callback:()=>{
                let handle = this.state.handle;
                handle && handle.updateList();
              }
            });
            this.setState({visible: false})
        //   }
        // }).catch(e=>{
        //   openNotificationWithIcon("error","提交失败","请检查填写是否正确");
        // })
    }
  };
  showAlert = () => {
    const duration = 3.5;
    if (this.props.deviceType_add.response) {
      let { state } = this.props.deviceType_add.response;
      if (state) {
        openNotificationWithIcon("success","提交成功","恭喜，提交成功！");
      } else {
        openNotificationWithIcon("error","提交失败，列表中已存在该设备类型！");
      }
      this.props.deviceType_add.response = null;
    }
  }

  showWindow = () => {
    const IotDeviceTypeWrapper = Form.create({ name: 'IotDeviceType' })(IotDeviceType);
    this.showAlert();
    return (
      <Modal
        visible={this.state.visible}
        title="详细"
        width="800px"
        destroyOnClose
        onCancel={() => {
          this.setState({ visible: false });
        }}
        footer={null}
      >
        <div>
          <Card className={styles.selectCard}>
            <IotDeviceTypeWrapper
              onSubmit={this.handleSubmit}
              disabled={this.state.disabled}
              result={this.state.row}
            />
          </Card>
        </div>
      </Modal>
    );
  };

  //订阅查看弹窗，显示该设备被哪些应用所订阅
  showSubFind = () => {
    return (
      <Modal
        visible={this.state.visibleFind}
        title="详细"
        width="1000px"
        destroyOnClose
        onCancel={() => {
          this.setState({ visibleFind: false });
        }}
        footer={null}
      >
        <div>
          <Card className={styles.selectCard}>
            <IotDeviceFind result={this.state.row} resEntity="subscriptiondevicetype"/>
          </Card>
        </div>
      </Modal>
    );
  };

  render() {
    return (
      <PageHeaderWrapper>
        {this.showWindow()}
        {this.showSubFind()}
        <Card bordered={true}>
          <AdvancedTable
            columns={this.columns}
            bordered
            // useMultiSelect
            updateFirst
            controllers={this.controllers}
            master={this.master}
            items={this.items}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
